<template>
  <div class="outside-list">
    <div class="search-box">
      <Row type="flex">
        <Row
          type="flex"
          justify="start"
        >
          <Col class="search-item">
          <span class="search-label">对账结果:</span>
          <Select
            v-model="checked"
            @on-change="searchList"
          >
            <Option
              v-for="item in checkedList"
              :value="item.value"
              :key="item.value"
            >{{ item.label }}</Option>
          </Select>
          </Col>
          <Col class="search-item">
          <span class="search-label">对账备注:</span>
          <Select
            v-model="errorType"
            @on-change="searchList"
          >
            <Option
              v-for="item in errorTypeList"
              :value="item.value"
              :key="item.value"
            >{{ item.label }}</Option>
          </Select>
          </Col>
          <Col class="search-item">
          <span class="search-label">对账日期:</span>
          <!-- <DatePicker
            type="datetimerange"
            :editable="false"
            format="yyyy-MM-dd HH:mm:ss"
            class="data-time-style"
            style="width:280px;"
            :value="payStartTime"
            @on-change="selectStartTime"
            @on-clear="clearStartTime"
            placement="bottom"
          >
          </DatePicker> -->
          <DatePicker
            type="date"
            :editable="false"
            format="yyyy-MM-dd"
            :value="payTime"
            placement="bottom"
            @on-clear="clearStartTime"
            @on-change="selectStartTime"
          >
          </DatePicker>
          </Col>
          <Col class="search-item">
          <Button
            class="search-btn"
            type="primary"
            @click="doSearch"
          >查询</Button>
          </Col>
          <Col class="search-item">
          <Button
            class="search-btn"
            @click="resetData"
          >重置</Button>
          </Col>
          <Col class="search-item">
          <Button type="primary" :disabled='disabledStatus'
            class="search-btn"
            @click="handleCheck"
          >手工对账</Button>
          </Col>
        </Row>
      </Row>
    </div>
    <div>
      <Table class="table-list" :columns="columns" :data="data" stripe :loading='loading' :height="this.tableHeight" ref="selection" @on-selection-change='selectItem'>
        <!-- 第三方支付/退款状态 -->
        <template slot-scope="{ row }" slot="outStatus">
          <!-- <span>{{ row.outStatus===1?"支付成功":row.outStatus===2?"创建":row.outStatus===3?"等待":row.outStatus===6?"准备取消":row.outStatus===7?"部分退款":row.outStatus===8?"退款完成":row.outStatus===9?"取消":"" }}</span> -->
          <span v-if="row.orderType ==='PAYMENT_ACCOUNT'">{{ row.outStatus===0?"未付款":row.outStatus===1?"付款成功":row.outStatus===2?"付款失败":row.outStatus===3?"付款中":row.outStatus===7?"部分退款":row.outStatus===8?"已退款":row.outStatus===9?"已取消":row.outStatus===10?"异常":"" }}</span>
          <span v-if="row.orderType ==='PAYMENT_REFUND'">{{ row.outStatus===0?"未退款":row.outStatus===1?"退款成功":row.outStatus===2?"退款失败":"" }}</span>
        </template>
        <!-- 支付/退款状态-->
        <template slot-scope="{ row }" slot="status">
          <!-- <span>{{ row.status===1?"支付成功":row.status===2?"创建":row.status===3?"等待":row.status===6?"准备取消":row.status===7?"部分退款":row.status===8?"退款完成":row.status===9?"取消":"" }}</span> -->
          <span v-if="row.orderType ==='PAYMENT_ACCOUNT'">{{ row.status===0?"未付款":row.status===1?"付款成功":row.status===2?"付款失败":row.status===3?"付款中":row.status===7?"部分退款":row.status===8?"已退款":row.status===9?"已取消":row.status===10?"异常":"" }}</span>
          <span v-if="row.orderType ==='PAYMENT_REFUND'">{{ row.status===0?"未退款":row.status===1?"退款成功":row.status===2?"退款失败":"" }}</span>
        </template>
        <!-- 支付类型 & 第三方支付类型 -->
        <template slot-scope="{ row }" slot="orderType">
          <span>{{ row.orderType==="PAYMENT_ACCOUNT"?"支付":row.orderType==="PAYMENT_REFUND"?"退款":"" }}</span>
        </template>
        <!-- 支付/退款方式 & 第三方支付方式-->
        <template slot-scope="{ row }" slot="payType">
          <!-- <span>{{ row.payType==="WEIXIN"?"微信":row.payType==="ALIPAY"?"支付宝":"" }}</span> -->
          <span>{{ row.payType===1?"微信":row.payType===2?"支付宝": row.payType===3?"POS刷卡":row.payType===4?"现金":row.payType===5?"对公转账":''}}</span>
        </template>
        <!-- 对账结果 -->
        <template slot-scope="{ row }" slot="resultType">
          <span>{{ row.resultType==="WAITING"?"异常待处理":row.resultType==="NORMAL"?"正常":row.resultType==="CHECKED"?"异常已处理":row.resultType==="SUSPENDING"?"挂起":"" }}</span>
        </template>
        <!-- 对账备注 -->
        <template slot-scope="{ row }" slot="remark">
          <!-- <span>{{ row.remark==="PAY_STATUS_DIFF"?"状态不一致":row.remark==="PAY_AMOUNT_DIFF"?"金额不一致":row.remark==="ACCOUNT_SHORT_DIFF"?"短款":row.remark==="ACCOUNT_LONG_DIFF"?"长款":"" }}</span> -->
          <span>{{row.remark}}</span>
        </template>
        <!-- 本地手续费 -->
        <template
          slot-scope="{ row }"
          slot="fee"
        >
          <span>{{ row.fee?row.fee:"0.00" }}</span>
        </template>
        <!-- 第三方手续费 -->
        <template
          slot-scope="{ row }"
          slot="outFee"
        >
          <span>{{ row.outFee?row.outFee:"0.00" }}</span>
        </template>
        <template slot-scope="{ row}" slot="action">
          <i v-if="row.resultType==='WAITING'" title="差错处理" class="iconsys iconchacuochuli" @click="errorHandling(row)"></i>
        </template>
      </Table>
      <Modal
        v-model="errorHandleModel"
        title="差错处理"
        :mask-closable="false"
        :closable="false"
      >
        <Input
          v-model="processRemark"
          type="textarea"
          :autosize="{minRows: 4,maxRows:6}"
          placeholder="输入相关描述"
          class="Row_content_input"
        />
        <div slot="footer">
          <Button
            type="text"
            @click="outsideCancel"
          >取消</Button>
          <Button
            type="primary"
            @click="outsideOk"
            :disabled="loadingModel"
            :loading="loadingModel"
          >确认</Button>
        </div>
      </Modal>
      <Row type="flex">
         <Col span="12" style="padding-left:24px;margin:20px 0;">
          <Button class="module-menu-margin" @click="handleSelectAll" :disabled='disabledStatus'>{{btnTitle}}</Button>
          <Button class="module-menu-margin" @click="handleErr" :disabled='disabledStatus'>差错处理</Button>
        </Col>
        <Col span="12">
        <div class="page-box">
          <Page
            :total="total"
            :current="pageIndex"
            :page-size="pageSize"
            @on-page-size-change="selectPageNum"
            @on-change="selectPageIndex"
            ref="pages"
            show-total
            show-sizer
          />
        </div>
        </Col>
      </Row>

    </div>
    <Drawer title="选择对账日期" v-model="checkStatus" width='324px' :transfer='false'>
      <Row type='flex' justify="center">
        <Col>
          <DatePicker type="date"  placeholder="请选择" style="width: 200px" :editable='false' :options="disabledData" v-model='reconciliationData'></DatePicker>
        </Col>
      </Row>
      <div class="demo-drawer-footer footer1">
          <Button style="margin-right: 15px" @click="checkStatus = false">取消</Button>
          <Button type="primary" @click="sureHandleDiy">确定</Button>
      </div>
    </Drawer>
  </div>
</template>
<script>
import { payBillList, payBillFix, getDiyStatus, handleDiy } from '@/api/pay/index'
import { formatDate } from '@/libs/tools'
export default {
  name: 'payment_check_outside_list',
  data () {
    return {
      payTime: formatDate(new Date(), 'yyyy-MM-dd'),
      reconciliationData: '', // 手工对账日期
      allStatus: true, // 全选状态
      btnTitle: '全选',
      selectArrry: [],
      checkStatus: false,
      disabledData: {
        disabledDate (date) {
          return date && date.valueOf() > Date.now() - 86400000
        }
      },
      disabledStatus: false, // 对账状态
      starTime: '',
      endTime: '',
      loading: true,
      checked: 'WAITING', // 对账结果
      errorType: '-1', // 对账备注
      total: 0,
      tableHeight: 0,
      loadingModel: false,
      processRemark: '', // 处理备注
      errorId: '', // 对账详情
      data: [], // 表数据
      errorHandleModel: false, // 差错处理弹窗显示
      // payStartTime: [
      //   formatDate(
      //     new Date(new Date().getTime() - 86400000 * 7),
      //     'yyyy-MM-dd hh:mm:ss'
      //   ),
      //   formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss')
      // ],
      // searchParam: {
      //   beginDate: formatDate(
      //     new Date(new Date().getTime() - 86400000 * 7),
      //     'yyyy-MM-dd hh:mm:ss'
      //   ), // 开始日期
      //   endDate: formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss') // 结束日期
      // },
      pageIndex: 1, // 偏移量
      pageSize: 10, // 每页条数
      checkedList: [
        { value: '-1', label: '全部' },
        { value: 'NORMAL', label: '正常' },
        { value: 'WAITING', label: '异常待处理' },
        { value: 'CHECKED', label: '异常已处理' }
      ], // 对账结果
      errorTypeList: [
        { value: '-1', label: '全部' },
        { value: 'SUCCESS', label: '正常' },
        { value: 'ACCOUNT_LONG_DIFF', label: '长款' },
        { value: 'ACCOUNT_SHORT_DIFF', label: '短款' },
        { value: 'PAY_AMOUNT_DIFF', label: '金额不一致' },
        { value: 'PAY_STATUS_DIFF', label: '状态不一致' }
      ],
      // 对账备注
      //   表头
      columns: [
        { type: 'selection', width: 60, fixed: 'left' },
        {
          title: '外部对账编号',
          key: 'id',
          minWidth: 160,
          fixed: 'left'
        },
        { title: '清算日期', key: 'billDate', minWidth: 120 },
        { title: '支付流水号/退款流水号', key: 'txId', minWidth: 250 },
        {
          title: '支付完成时间/退款完成时间',
          key: 'txTime',
          minWidth: 200
        },
        { title: '支付类型', slot: 'orderType', minWidth: 150 },
        { title: '支付/退款方式', slot: 'payType', minWidth: 150 },
        { title: '支付/退款状态', slot: 'status', minWidth: 150 },
        { title: '第三方支付类型', slot: 'orderType', minWidth: 150 },
        { title: '第三方支付方式', slot: 'payType', minWidth: 150 },
        { title: '第三方支付/退款状态', slot: 'outStatus', minWidth: 150 },
        { title: '本地支付/退款金额', key: 'outAmount', minWidth: 150 },
        { title: '第三方支付/退款金额', key: 'amount', minWidth: 150 },
        { title: '本地费率', key: 'rate', minWidth: 150 },
        { title: '第三方费率', key: 'outRate', minWidth: 150 },
        { title: '本地手续费', slot: 'fee', minWidth: 150 },
        { title: '第三方手续费', slot: 'outFee', minWidth: 150 },
        { title: '对账结果', slot: 'resultType', minWidth: 150 },
        { title: '对账备注', slot: 'remark', minWidth: 150 },
        { title: '处理备注', key: 'processRemark', minWidth: 150, tooltip: true }
      ]
    }
  },
  watch: {
    selectArrry (val) {
      if (val.length === this.data.length && this.data.length !== 0) {
        this.btnTitle = '取消全选'
        this.allStatus = false
      } else {
        this.btnTitle = '全选'
        this.allStatus = true
      }
    },
    checkStatus (val) {
      if (!val) {
        this.reconciliationData = ''
      }
    }
  },
  methods: {
    // 手工对账
    sureHandleDiy () {
      if (this.reconciliationData) {
        handleDiy({
          billDate: formatDate(this.reconciliationData, 'yyyy-MM-dd'),
          recheck: true
        }).then(res => {
          if (res.data.status === 200) {
            this.checkStatus = false
            this.getCheckStatus()
          } else {
            this.$Message.error(`${res.data.error}`)
          }
        })
      } else {
        this.$Message.error('请选择对账日期')
      }
    },
    // 获取手工对账的任务状态
    getCheckStatus () {
      getDiyStatus().then(res => {
        if (res.data.status === 200) {
          this.disabledStatus = res.data.data.isRunning
        } else {
          this.$Message.error(`${res.data.message}`)
        }
      })
    },
    handleErr () {
      if (this.selectArrry.length > 0) {
        let flag = true
        let ids = []
        this.selectArrry.forEach(item => {
          ids.push(item.id)
          if (item.resultType !== 'WAITING') {
            flag = false
          }
        })
        if (flag) {
          payBillFix({
            ids: ids
            // processRemark: ''
          }).then(res => {
            if (res.data.status === 200) {
              this.$Message.success('批量操作成功！')
              this.selectArrry = []
              // 此处需刷新吗??????????
              this.searchList()
            } else {
              this.$Message.error(`${res.data.message}`)
            }
          })
        } else {
          this.$Message.error('请选择异常待处理的数据')
        }
      } else {
        this.$Message.error('请选择差错处理数据')
      }
    },
    handleSelectAll () {
      this.$refs.selection.selectAll(this.allStatus)
    },
    selectItem (val) {
      this.selectArrry = val
    },
    handleCheck () {
      // if (this.data.length > 0) {
      this.checkStatus = true
      // } else {
      //   this.$Message.error('没有可手工对账的数据')
      // }
    },
    doSearch () {
      this.starTime = this.searchParam.beginDate
      this.endTime = this.searchParam.endDate
      this.searchList()
    },
    // 列表数据
    searchList () {
      this.tableHeight = 0
      this.loading = true
      payBillList({
        // ...this.searchParam,
        merchantId: this.$store.state.user.merchantId,
        // beginDate: this.starTime,
        // endDate: this.endTime,
        billDate: this.payTime,
        resultType: this.checked === '-1' ? '' : this.checked,
        errType: this.errorType === '-1' ? '' : this.errorType,
        offset: (this.pageIndex - 1) * this.pageSize, // 分页OFFSET
        limit: this.pageSize
      })
        .then(res => {
          if (res.data.status === 200) {
            this.selectArrry = []
            this.loading = false
            this.data = res.data.data
            this.total = res.data.totalCount
            if (res.data.data && res.data.data.length >= 10) {
              this.tableHeight = 537
            }
          } else {
            this.loading = false
            this.$Message.error(`${res.data.message}`)
          }
        })
        .catch(err => {
          this.loading = false
          this.$Message.error(`${err}`)
        })
    },
    // 分页行数
    selectPageNum (num) {
      this.pageIndex = 1
      this.pageSize = num
      this.searchList()
    },
    // 分页页数
    selectPageIndex (val) {
      this.pageIndex = val
      this.searchList()
    },
    // 选择开始时间
    selectStartTime (val) {
      // this.searchParam.beginDate = val[0] // 退款发起时间开始
      // this.searchParam.endDate = val[1] // 退款发起时间结束
      this.payTime = val
      this.searchList()
    },

    // 清空开始时间
    clearStartTime () {
      // this.searchParam.beginDate = '' // 退款发起时间开始
      // this.searchParam.endDate = '' // 退款发起时间结束
      // this.starTime = ''
      // this.endTime = ''
      this.payTime = ''
    },
    // 差错处理
    errorHandling (row) {
      if (this.disabledStatus) {
        this.$Message.error('手工对账中,不可操作！')
      } else {
        this.errorHandleModel = true
        this.errorId = row.id
        this.processRemark = '' // 处理备注
      }
    },
    outsideOk () {
      this.loadingModel = true
      if (this.processRemark !== '') {
        payBillFix({
          ids: [this.errorId],
          processRemark: this.processRemark
        })
          .then(res => {
            if (res.data.status === 200) {
              this.loadingModel = false
              this.errorHandleModel = false
              this.$Message.success('处理成功！')
              this.searchList()
            } else {
              this.loadingModel = false
              this.$Message.error(`${res.data.message}`)
            }
          })
          .catch(err => {
            this.loadingModel = false
            this.$Message.error(`${err}`)
          })
      } else {
        this.$Message.error({
          content: `请输入相关描述`,
          duration: 1
        })
        setTimeout(() => {
          this.loadingModel = false
        }, 1000)
      }
    },
    // 取消
    outsideCancel () {
      this.errorHandleModel = false
      this.errorId = ''
      this.processRemark = '' // 处理备注
    },
    // 重置
    resetData () {
      this.loading = true
      // this.checked = '-1' // 对账结果
      // this.checked = 0
      this.payTime = formatDate(new Date(), 'yyyy-MM-dd') // 对账日期
      this.checked = 'WAITING'
      this.errorType = '-1' // 对账备注
      this.total = 0
      this.pageIndex = 1
      this.pageSize = 10
      this.processRemark = '' // 处理备注
      this.errorInfo = {} // 对账详情
      this.errorHandleModel = false // 差错处理弹窗显示
      // this.payStartTime = [
      //   formatDate(
      //     new Date(new Date().getTime() - 86400000 * 7),
      //     'yyyy-MM-dd hh:mm:ss'
      //   ),
      //   formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss')
      // ]
      this.searchParam = {
        beginDate: formatDate(
          new Date(new Date().getTime() - 86400000 * 7),
          'yyyy-MM-dd hh:mm:ss'
        ), // 开始日期
        endDate: formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss'), // 结束日期
        offset: 1, // 偏移量
        limit: 10 // 每页条数
      }
      this.starTime = formatDate(
        new Date(new Date().getTime() - 86400000 * 7),
        'yyyy-MM-dd hh:mm:ss'
      )
      this.endTime = formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss')
      this.searchList()
    }
  },
  created () {
    if (this.hasPermission(['moms:pay:fixexternalcheck'])) {
      this.columns.push({ title: '操作', slot: 'action', fixed: 'right', minWidth: 100 })
    }
  },
  mounted () {
    this.starTime = formatDate(
      new Date(new Date().getTime() - 86400000 * 7),
      'yyyy-MM-dd hh:mm:ss'
    )
    this.endTime = formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss')
    this.searchList()
    this.getCheckStatus()
  }
}
</script>
<style lang="less">
.outside-list {
  .data-time-style {
    .ivu-input-wrapper {
      width: 280px;
    }
  }
  .ivu-table-tip {
    span {
      position: absolute;
      width: 100px;
      left: 50%;
      margin-left: -50px;
    }
  }
  .footer1{
    width: 100%;
    position: absolute;
    bottom: 0;
    left: 0;
    border-top: 1px solid #e8e8e8;
    padding: 10px 16px;
    text-align: right;
    background: #fff;
  }
}
</style>
